package com.fuyun.rpc.util;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @Author fuyun。
 * @Date 2025/8/21 17:42。
 * @Description: TODO。
 **/

public class ThreadPoolUtils {
    private static final Map<String, ExecutorService> THREAD_POOL_MAP = new ConcurrentHashMap<>();
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CPU_POOL_SIZE = CPU_COUNT + 1;
    private static final int IO_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 60;
    private static final int QUEUE_SIZE = 100;


    public static ExecutorService createExecutorService(String poolName) {
        if (THREAD_POOL_MAP.containsKey(poolName)) {
            return THREAD_POOL_MAP.get(poolName);
        }
        ExecutorService executorService = new ThreadPoolExecutor(
                CPU_POOL_SIZE,
                CPU_POOL_SIZE,
                KEEP_ALIVE,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(QUEUE_SIZE),
                ThreadFactoryBuilder.create().setNamePrefix(poolName).build());
        THREAD_POOL_MAP.put(poolName, executorService);
        return executorService;
    }

    public static void shutdown() {
        THREAD_POOL_MAP.forEach((s, executorService) -> {
            executorService.shutdown();
        });
    }
}
